<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->
    

    <div class="main-wrap">


      <!-- 加载中 -->
      <div class="loading-wrap" v-if="code===1">
        <van-loading
          color="#3296fa"
          vertical
        >加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-if="code===2">
        <!-- 文章标题 -->
        <h1 class="article-title">{{articleInfo.title}}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="articleInfo.aut_photo"
          />
          <div slot="title" class="user-name">{{articleInfo.aut_name}}</div>
          <div slot="label" class="publish-date">{{articleInfo.pubdate | relativeTime }}</div>

          <!----------关注用户组件 S--------------->
          <!-- 组件v-model的场景： -->
          <!-- 子组件既要用父组件传递进入的数据，子组件又要改变这个数据 -->
          <!-- v-model本质是 自定义属性value和自定义事件input的语法糖 -->
          <!-- 一个组件只能有一个v-model -->
          <!-- <FollowUser 
            :author-id="articleInfo.aut_id"
            :value="articleInfo.is_followed"
            @input="articleInfo.is_followed=$event"
          /> -->
          <FollowUser 
            :author-id="articleInfo.aut_id"
            v-model="articleInfo.is_followed"
          />
          <!----------关注用户组件 E--------------->
         
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div class="article-content markdown-body" ref="content" v-html="articleInfo.content"></div>
        <van-divider>正文结束</van-divider>
        
        <!---------------------文章评论列表组件 S----------------------------------->
        <comment-list
          @open-reply="openReply"
          :list="commentListData"
          :source-id="articleId"
          @update-total="commentTotalCount=$event"
        />
        <!---------------------文章评论列表组件 E----------------------------------->


        <!---------------------对文章进行评论 S----------------------------------->
        <van-popup v-model="isPostShow" position="bottom">
          <comment-post  
            :target="articleId"
            @update-list="updateList"
          ></comment-post>
        </van-popup>
        <!---------------------对文章进行评论 E----------------------------------->


        <!---------------------评论回复组件 S----------------------------------->
        <van-popup v-model="isReplyShow" position="bottom" style="height:100%;">
          <comment-reply
            @close="isReplyShow=false"
            v-if="isReplyShow"
            :cur-comment="clickCurrentComment"
          ></comment-reply>
        </van-popup>
        <!---------------------评论回复组件 E----------------------------------->

        


        <!-- 底部区域 -->
        <div class="article-bottom">
            <van-button
                class="comment-btn"
                type="default"
                round
                size="small"
                @click="isPostShow=true"
              >写评论</van-button>
            <van-icon
                name="comment-o"
                :badge="commentTotalCount"
                color="#777"
              />
            <!----------文章收藏组件 S--------------->  
            <!-- <CollectArticle
                :value="articleInfo.is_collected"
                @input="articleInfo.is_collected=$event"
                :article-id="articleId"
             /> -->
             <CollectArticle
                v-model="articleInfo.is_collected"
                :article-id="articleId"
             />
            <!----------文章收藏组件 S--------------->

            <!----------文章点赞组件 S--------------->  
            <!-- <ZanArticle
              :zan="articleInfo.attitude"
              :article-id="articleId"
              @update:zan="articleInfo.attitude=$event"
            /> -->
            <!-- .sync 修饰符的意思是实现父子组件双向绑定，作用和v-model完全一样 -->
            <!-- 一个组件只能有1个v-model 可以有很多个.sync修饰符 -->
            <!-- 本质是一个语法糖： -->
            <!-- 
                子组件里面：   ① props:['属性名']  ② this.$emit('update:属性名',新值)
                父组件： <组件 :属性名="变量" @update:属性名="变量=$event"  />
                       简写：   <组件 :属性名.sync="变量"  />
 
             -->
            <ZanArticle
              :zan.sync="articleInfo.attitude"
              :article-id="articleId"
            />
            <!----------文章点赞组件 S--------------->
            
            <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->   
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-if="code===3">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-if="code===4">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="initData">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） --> 
    </div>    
  </div>
</template>

<script>
// $route.params.articleId 读取文章ID数据

import  { getArticleDetail } from '@/api/article'
import FollowUser from '@/components/follow-user'
import CollectArticle from '@/components/collect-article'
import ZanArticle from '@/components/zan-article'
import CommentList from './components/comment-list'
import CommentPost from './components/comment-post.vue'
import CommentReply from './components/comment-reply.vue'

// 导入第三方的文章正文样式文件
import './github-markdown.css'
// 导入图片预览函数
import { ImagePreview } from 'vant'

// ImagePreview({ images:[图片地址数组],startPosition:开始预览的图片索引 })
export default {
  name: 'ArticleIndex',
  provide(){
    return {
      articleId:this.articleId
    }
  },
  components: {
    FollowUser,CollectArticle,ZanArticle,CommentList,
    CommentPost,
    CommentReply
  },
  props: {
    // 使用props获取动态路由的数据  
    articleId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      articleInfo:{},
      code:1,  // 1 处于加载中    2 加载成功   3 404错误   4 服务器异常
      commentTotalCount:'', // 文章评论的总数量
      isPostShow:false,
      commentListData:[], // 文章的评论列表
      isReplyShow:false,
      clickCurrentComment:{} // 点击的评论项信息
    }
  },
  created () {
    this.initData()
  },
  methods: {
    async initData(){
      try {
        this.code = 1
        let { data } = await getArticleDetail(this.articleId)
        this.articleInfo = data.data
        this.code = 2
        // 页面的渲染是耗时的，是异步的任务！
        // 不能直接在下方去读取节点内容
        //  console.log(this.$refs.content); // 读取不到的是 undefined
        this.$nextTick(()=>{
          this.bindImgClick()
        })
      } catch (error) {
        if(error &&  error.response && error.response.status === 404) this.code = 3  
        this.code = 4
      }
    },
    bindImgClick(){
       // 1. 获取到容器的原生DOM节点
      // console.log(this.$refs.content);
      // 2. 获取文章正文容器内的所有图片节点
      const imgNode = this.$refs.content.querySelectorAll('img')
      // 3. 遍历取出图片地址和绑定点击事件
      const imgUrls = []
      imgNode.forEach((img,idx) => {
        imgUrls.push(img.src)
        img.onclick = ()=>{
          ImagePreview({
            images:imgUrls,
            startPosition:idx
          })
        }
      });
    },
    // 将数据放到评论列表顶部
    updateList(val){
      this.isPostShow = false
      this.commentListData.unshift(val.new_obj)
    },
    // 打开回复组件
    openReply(val){
      this.clickCurrentComment = val
      this.isReplyShow = true
    }
  },
}
</script>

<style scoped lang="less">

.article-container {
  .main-wrap {
    position: fixed;
    z-index: 1;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>